package com.zhangx.datastructure.stacklist;

/**
 *  循环队列-顺序循环队列
 *  P116
 */
public class CircleQueue {

    MyQueue queue;

    int MAX_SIZE = 5;

    @Override
    public String toString() {
        return queue.toString();
    }

    //
    static class MyQueue{
        int[] data;
//        头
        int front;
//        尾
        int rear;

        @Override
        public String toString() {
            String s = "front="+front+";rear="+rear + ";data=";
            for (int i = 0; i < data.length; i++) {
                s = s+ data[i] + ",";
            }
            return s;
        }
    }

    public void init(){
        queue = new MyQueue();
        queue.data = new int[MAX_SIZE];
        queue.front = 0;
        queue.rear = 0;
    }

    /**
     * 计算队列长度 （rear-front+QueueSize）%QueueSize
     * @return
     */
    public int length(){
        int len = (queue.rear-queue.front+queue.data.length)%queue.data.length;
        return len;
    }

    /**
     * 判断队列满 (rear+1)%QueueSize == front
     * @param d
     */
    public void push(int d){
        /*如果没满*/
        if ((queue.rear+1)%MAX_SIZE == queue.front){
            System.out.println("队列已满");
        }else {
            queue.data[queue.rear] = d;
//            转到尾就从头循环
            queue.rear = (queue.rear +1)%MAX_SIZE;
        }
    }

    public int pop(){
        if (queue.front == queue.rear){
            System.out.println("空队列");
            return -99;
        }

        int d = queue.data[queue.front];
        queue.data[queue.front] = 0;
        queue.front  = (queue.front + 1) % MAX_SIZE;

        return d;
    }

    public static void main(String[] args) {
        CircleQueue queue = new CircleQueue();
        queue.init();
        queue.push(1);
        System.out.println(queue);
        queue.push(2);
        System.out.println(queue);
        queue.push(3);
        System.out.println(queue);
        queue.push(4);
        System.out.println(queue);
        System.out.println(queue.pop());;
        System.out.println(queue);
    }
}
